package com.zlz.m3u8download.bean;

import com.alibaba.fastjson2.JSON;
import lombok.Data;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;

/**
 * @author zhulinzhong
 * @version 1.0 CreateTime:2019/10/21 9:59
 */
@Data
public class ResultSet<T> implements Serializable {

    private static final long serialVersionUID = -8110766448154376759L;

    /**
     * 状态码
     */
    private Integer code;

    /**
     * 返回的消息
     */
    private String message;

    /**
     * 返回的实体
     */
    private T data;

    public ResultSet(String message, Integer code) {
        this.message = message;
        this.code = code;
    }

    public ResultSet(String message, Integer code, T data) {
        this.message = message;
        this.code = code;
        this.data = data;
    }

    /**
     * 返回成功的消息
     *
     * @return ResultSet
     */
    public static <T> ResultSet<T> success() {
        return new ResultSet<>("success", 0);
    }

    /**
     * 返回成功的消息
     *
     * @param entity entity
     * @return ResultSet
     */
    public static <T> ResultSet<T> success(T entity) {
        return new ResultSet<>("success", 0, entity);
    }

    /**
     * 返回失败的消息数据
     *
     * @param code    code
     * @param message message
     * @return ResultSet
     */
    public static <T> ResultSet<T> error(Integer code, String message) {
        return new ResultSet<>(message, code);
    }

    /**
     * 返回失败的消息数据
     *
     * @return ResultSet
     */
    public static <T> ResultSet<T> error() {
        return new ResultSet<>("fail", -1);
    }

    @Override
    public String toString() {
        return toJSONString();
    }

    public String toJSONString() {
        String data = this.data == null ? "" : ",\"data\":" + JSON.toJSONString(this.data);
        return "{" +
                "\"code\":" + code +
                ",\"message\":" + "\"" + message + "\"" +
                data +
                '}';
    }

    public byte[] toJSONByte() {
        return toJSONString().getBytes(StandardCharsets.UTF_8);
    }

}
